package org.dromara.mp.handler;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;

import java.util.Map;

/**
 * 微信公众号消息处理器抽象类
 *
 * @author ruoyi
 */
@Slf4j
public abstract class AbstractHandler implements WxMpMessageHandler {

    /**
     * 构建文本消息
     *
     * @param content   消息内容
     * @param wxMessage 微信消息
     * @param service   微信服务
     * @return 文本消息
     */
    protected WxMpXmlOutTextMessage buildTextMessage(String content, WxMpXmlMessage wxMessage, WxMpService service) {
        return WxMpXmlOutTextMessage.TEXT().content(content)
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .build();
    }

    /**
     * 记录日志
     *
     * @param wxMessage 微信消息
     */
    protected void logMessage(WxMpXmlMessage wxMessage) {
        log.info("接收到微信消息：{}", wxMessage.toString());
    }

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context,
                                    WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        logMessage(wxMessage);
        return doHandle(wxMessage, context, wxMpService, sessionManager);
    }

    /**
     * 具体的消息处理逻辑
     *
     * @param wxMessage      微信消息
     * @param context        上下文
     * @param wxMpService    微信服务
     * @param sessionManager 会话管理器
     * @return 回复消息
     */
    protected abstract WxMpXmlOutMessage doHandle(WxMpXmlMessage wxMessage,
                                                  Map<String, Object> context,
                                                  WxMpService wxMpService,
                                                  WxSessionManager sessionManager);
}
